import json
from datetime import datetime, timedelta

import jwt
from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from U1.models import *


@csrf_exempt
def login(request):
    data = json.loads(request.body)
    #校验为空
    if data['username'] =='' or data['password']=='':
        return JsonResponse({
            'msg':'账号和密码不能为空'
        })
    #校验账号是否存在
    if User.objects.filter(username=data['username']).exists()==False:
        return JsonResponse({
            'msg':'账号不存在'
        })
    a = User.objects.get(username=data['username'])
    #校验密码是否正确
    if a.password!=data['password']:
        return JsonResponse({
            'msg':'密码错误'
        })
    #token设置
    mi = '123456'
    t = datetime.now()+timedelta(hours=2)
    pay = {
        'username':a.username,
        'password':a.password,
        'exp':int(t.timestamp())
    }
    token = jwt.encode(pay,mi)
    return JsonResponse({
        'msg':'登录成功',
        'token':token
    })
@csrf_exempt
#设备分类接口
def get_sbfl(request):
    data = Sbfl.objects.all()
    l=[]
    for i in data:
        l.append({
            'flname':i.flname,
            'id':i.id
        })
    return JsonResponse({
        'msg':'设备分类查询成功',
        'data':l
    })

@csrf_exempt
def create_sbxx(request):
    data = json.loads(request.body)
    a = Sbxx.objects.create(
        sbname=data['sbname'],
        numbers=data['numbers'],
        sbflid_id=data['sbflid_id'],
        price=data['price'],
        integer=data['integer'],
        status=data['status']
    )
    return JsonResponse({
        'msg':'添加成功',
        'data':model_to_dict(a)
    })
def delete_sbxx(request,id=None):
    Sbxx.objects.get(id=id).delete()
    return JsonResponse({
        'msg':'设备已删除'
    })
@csrf_exempt
def update_sbxx(request,id=None):
    u = Sbxx.objects.get(id=id)
    # 获取json信息
    data = json.loads(request.body)
    u.sbname = data['sbname']
    u.sbflid_id = data['sbflid_id']
    u.price = data['price']
    u.integer = data['integer']
    u.status = data['status']
    #修改后保存
    u.save()
    return JsonResponse({
        'msg':'设备信息修改成功',
        'data':model_to_dict(u)
    })

def get_sbxx(request):
    data = Sbxx.objects.all()
    sbname = request.GET.get('sbname')
    sbflid_id = request.GET.get('sbflid_id')
    page = request.GET.get('page',1)
    size = request.GET.get('size')or 10
    if sbname:
        data = data.filter(sbname=sbname)
    if sbflid_id:
        data = data.filter(sbflid_id=sbflid_id)
    data = Paginator(data,size).get_page(page)
    total = len(data)
    l = []
    for i in data:
        l.append({
            'sbname': i.sbname,
            'numbers': i.numbers,
            'sbflid_id':i.sbflid_id,
            'price':i.price,
            'integer':i.integer,
            'status':i.status
        })
    return JsonResponse({
        'msg': '设备信息查询成功',
        'data': l,
        'total':total
    })

@csrf_exempt
def create_jyjl(request):
    data = json.loads(request.body)
    token = request.META.get('HTTP_TOKEN')
    mi = '123456'
    t = jwt.decode(token,mi,algorithms=['HS256'])
    a = Jy.objects.create(
        sbid_id = data['sbid_id'],
        jinteger = data['jinteger'],
        jyr = t['username'],
        jdatetime = data['jdatetime'],
        ydatetime = data['ydatetime'],
        sdatetime = data['sdatetime']
    )
    b = Sbxx.objects.get(id = data['sbid_id'])
    b.integer=int(b.integer)-int(data['jinteger'])
    b.save()
    return JsonResponse({
        'msg':'添加成功',
        'data':model_to_dict(a)
    })
def get_jyjl(request):
    data = Jy.objects.all()
    sbname = request.GET.get('sbname')
    start = request.GET.get('start')
    end = request.GET.get('end')
    page = request.GET.get('page',1)
    size = request.GET.size('size') or 10
    data = Paginator(data,size).get_page(page)
    l = []
    for i in data:
        l.append({
            "sbid_id":i.sbid_id,
            "jinteger":i.jinteger,
            "jyr":i.jyr,
            "jdatetime":i.jdatetime,
            "ydatetime":i.ydatetime,
            "sdatetime":i.sdatetime
        })
    return JsonResponse({
        'msg':'查询借阅记录成功',
        'data':l
    })
